<?php


namespace app\admin\model;


use think\Db;

class OrderGoodsModel extends BaseModel
{
    protected $name='order_goods';

    public function doAddData($param){

        $goods=$param['goods'];
        $goods_info=[];
        $this->startTrans();
        try {
            foreach ($param['goods'] as $key => &$val) {
                if (!empty($val['dele_id'])) {
                    $this->where(['id'=>$val['dele_id']])->delete();
                } else {
                    $arr = [
                        'type' => 0,
                        'cate_name' => $val['cate_name'],
                        'order_id' => $param['order_id'],
                        'customer_id' => $param['customer_id'],
                        'deceased_id' => $param['deceased_id'],
                        'goods_id' => $val['goods_id'],
                        'goods_name' => $val['goods_name'],
                        'goods_price' => $val['goods_price'],
                        'num' => $val['num'],
                        'discount_price' => 0,
                        'total_price' => $val['goods_price'] * $val['num'],
                        'actual_amount' => $val['goods_price'] * $val['num'],
                        'add_user' => cmf_get_current_admin_id(),
                        'add_time' => time(),
                    ];
                    // 判断商品表数量够不够
                    $goods = Db::name('goods')->where(['id' => $val['goods_id']])->find();

                    if ($val['num'] > $goods['stock']) {
                        $this->rollback();
                        $this->error = $val['goods_name'] . '库存不足';
                        return false;
                    }
                    if (!empty($val['id'])){
                        $result_id = $this->update($arr, ['id' => $val['id']]);
                    } else {
                        $result_id = $this->insertGetId($arr);
                    }
                    if ($result_id) {
                        Db::name("goods")->where(['id' => $val['goods_id']])->setDec('stock', $val['num']);
                    }
                    $goods_info[] = $arr;
                }
            }
//            exit(json_encode($goods_info));
            $this->commit();
            return true;
        }catch(\Exception $exception){
            $this->rollback();
            $this->error='添加失败';
            return false;
        }
    }

}